﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyLocalChurch.Constants;
using MyLocalChurch.Models;
using MyLocalChurch.Models.Enumerations;
using RKConsulting.Helpers;
using RKConsulting.Web.Helpers;

namespace MyLocalChurch.ChurchServices
{
    public partial class CreateChurchService : System.Web.UI.Page
    {
        private readonly MyContext _context = MyContextSingleton.Instance;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
                return;

            ddlDayOfWeek.BindEnumValues<DayOfWeek>();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (!Page.IsValid)
                return;

            var churchService = new ChurchService
            {
                DayOfWeek = EnumHelper.Parse<DayOfWeek>(ddlDayOfWeek.SelectedValue),
                StartTime = txtStartTime.Text,
                Description = txtDescription.Text,
                CreatedBy = SystemConstants.User,
                CreatedDate = DateTime.Now
            };

            _context.ChurchServices.Add(churchService);
            _context.SaveChanges();

            Response.Redirect("Default.aspx");
        }

        protected void cvStartTime_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (_context.ChurchServices.Any(cs => cs.StartTime == txtStartTime.Text))
                args.IsValid = false;
        }
    }
}